//
//  ViewController.m
//  高仿暴走斗图
//
//  Created by huangsongyao on 16/3/4.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "HSYRootViewController.h"
#import "TestVC.h"
#import "UIAlertView+RAC.h"
#import "HSYBaseViewController+Alert.h"
#import "TestCollectionVC.h"
#import "RootVCCell.h"
#import "HSYRootVM.h"
#import "HSYBaseViewController+Device.h"
#import "UIButton+RAC.h"
#import "HSYBaseCardNavigationController+Animation.h"
#import "HSYAlertView.h"
#import "NSString+RACKeyPathUtilities.h"
#import "UIImage+Canvas.h"
#import "HSYFlipView.h"
#import "NSObject+RACDescription.h"
#import "UITextField+RAC.h"
#import "UIScrollView+RAC.h"
#import "UIScrollView+RACSignal.h"
#import "HSYProgressView.h"
#import "SchoCustomSlider.h"
#import "HSYCustomPhotoViewController+ALAsset.h"
#import "HSYBaseViewController+ExportSession.h"
#import "TestVideoPlayerViewController.h"
#import "HSYWaterWaveView+Show.h"
#import "HSYRootViewController+TopButton.h"
#import "TestFMDBOperationViewController.h"

@interface HSYRootViewController ()<HSYCustomBaseTableViewMoveCellDelegate>
@property (nonatomic, strong) HSYRootVM *viewModel;
@property (nonatomic, strong) HSYCustomBaseTableViewMoveCell *signCell;
@end

static NSString *Identifier = @"IdentifierCell";

@implementation HSYRootViewController

- (instancetype)init {
    
    if (self = [super init]) {
        
        self.viewModel = [[HSYRootVM alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.isCanReflesh = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNavigationBarRightButtonWithTitle:@"test"];
    
    @weakify(self);
    self.selectIndexPathCell = ^(id tableViewCell, NSIndexPath *indexPath) {
        
        @strongify(self);
        if (self.signCell) {
            [self.signCell closeMoveCellWithAnimated:YES];
        }
        NSLog(@"index");
    };
    
    UIColor *firstWaveColor = [UIColor colorWithRed:146/255.0 green:148/255.0 blue:216/255.0 alpha:1.0];
    UIColor *secondWaveColor = [UIColor colorWithRed:84/255.0 green:87/255.0 blue:197/255.0 alpha:1.0];
    [HSYWaterWaveView showWaterWaveViewForWaveParamter:@{
                                                         
                                                         @(kWaterWaveParamterKeyTypeWaveSpeed)          : @(0.3),
                                                         @(kWaterWaveParamterKeyTypeWaveUpGrowth)       : @(0.85),
                                                         @(kWaterWaveParamterKeyTypeWaveFirstColor)     : firstWaveColor,
                                                         @(kWaterWaveParamterKeyTypeWaveSecondColor)    : secondWaveColor,
                                                         @(kWaterWaveParamterKeyTypeWaveUpMaxPercent)   : @(0.9f),
                                                         
                                                         }waveFrame:CGRectMake(0, 100, IPHONE_WIDTH, 150) showInView:self.view];
    
    
    self.clickRightButtonBlock = ^(UIButton *button) {
     
        @strongify(self);
//        NSURL *url = [[NSBundle mainBundle] URLForResource:@"150511_JiveBike" withExtension:@"mov"];
        
        //http://baobab.wdjcdn.com/1451897812703c.mp4
        TestVideoPlayerViewController *vc = [[TestVideoPlayerViewController alloc] initWithVideoUrlString:@"http://scho.oss-cn-hangzhou.aliyuncs.com/05FC2C735ACF08EA8B32EA644E0337BD.mp4"];
        [self pushToViewController:vc animated:YES];
        
//        TestFMDBOperationViewController *vc = [[TestFMDBOperationViewController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
        
//        TestCollectionVC *vc = [[TestCollectionVC alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];

//        [HSYCustomPhotoViewController rac_openAssetPhotoResourcesLibraryWithAssetType:kALAssetTypePhoto presentBlock:^(HSYBaseCardNavigationController *nav) {
//            @strongify(self);
//            [self presentViewController:nav animated:YES completion:^{
//                
//            }];
//        } completion:^(id x) {
//            NSLog(@"x : %@", x);
//        }];
    
        
        
//        NSString *temp = GET_FILES_PATH(@"IMG_0203", @"m4v");
//        [[[self rac_changeVideoMOVToMP4:[NSURL URLWithString:temp]] deliverOn:RACScheduler.mainThreadScheduler] subscribeNext:^(id x) {
//            
//            NSLog(@"x : %@", x);
//            
//        } error:^(NSError *error) {
//            
//            NSLog(@"error :%@", error);
//            
//        } completed:^{
//            @strongify(self);
//            [self cameraDeviceDismissViewControllerForAnimated:YES completion:nil];
//        }];
        
//        [[[self rac_openSystemResourcesForDeviceType:kSystemAnimationTypeCamera withCompletion:^(UIViewController *viewController) {
//            
//            [NSObjcGCD gcd_MainThreadExecutionForBlock:^{
//                @strongify(self);
//                [self presentViewController:viewController animated:YES completion:^{
//                    
//                }];
//            }];
//            
//        } dismissCompletion:^{
//            
//            //dismiss结束后的block
//            
//        }] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDictionary *dic) {
//            
//            //回调
////            UIImage *image = dic[@"UIImagePickerControllerEditedImage"];
////            NSLog(@"image: %@", image);
//            @strongify(self);
//            [[[self rac_changeVideoMOVToMP4:dic[@"UIImagePickerControllerMediaURL"]] deliverOn:RACScheduler.mainThreadScheduler] subscribeNext:^(id x) {
//                
//                NSLog(@"x : %@", x);
//                
//            } error:^(NSError *error) {
//                
//                NSLog(@"error :%@", error);
//                
//            } completed:^{
//                @strongify(self);
//                [self cameraDeviceDismissViewControllerForAnimated:YES completion:nil];
//            }];
//        }];
    };
    
//    [[[self.tableView rac_didScroll] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
//       
//        NSLog(@"x :%@", x);
//    }];
//
//
//    [[[UIAlertView rac_showAlertViewWithTitle:@"" message:@"" cancelButtonTitle:@"test" otherButtonTitles:nil] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
//        NSLog(@"x : %@", x);
//    }];
    
    [self.tableView registerClass:[RootVCCell class] forCellReuseIdentifier:Identifier];


    self.topButton = [UIButton rac_createButtonForBackgroundImage:CREATE_IMG(SHOWVC_DOT)
                                            withHighImage:CREATE_IMG(SHOWVC_DOT)
                                                    title:nil
                                                highTitle:nil
                                         signalCompletion:^(id x) {
                                             @strongify(self);
                                             [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                                         }];
    self.topButton.alpha = 0.0;
    self.topButton.layer.cornerRadius = 25.0;
    self.topButton.frame = CGRectMake(IPHONE_WIDTH - 60, IPHONE_HEIGHT - 183, 50, 50);
    [self.view insertSubview:self.topButton aboveSubview:self.tableView];

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

/**
 *  条件锁
 */
- (void)conditionLockInvokeForConds:(NSInteger)conds {
    
    id conditionLock = [[NSConditionLock alloc] initWithCondition:conds];//NS_DESIGNATED_INITIALIZER
    while(true) {
        
        [conditionLock lockWhenCondition:conds];
        //生产数据
        [conditionLock unlockWithCondition:conds];
    }
}

/**
 *  递归锁
 */
- (void)recursiveLockInvokeBlock {
    
    NSRecursiveLock *lock = [[NSRecursiveLock alloc] init];                             //创建一个递归锁
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{    //创建一个线程，线程执行内容为递归某一block
        
        static void (^RecursiveMethod)(int);                                            //执行的block
        RecursiveMethod = ^(int value) {
            
            [lock lock];                                                                //如果block被执行时添加一个递归锁
            if (value > 0) {                                                            //value为正数时，执行
                
                NSLog(@"value = %d", value);
                sleep(value-1);                                                         //延迟执行
                RecursiveMethod(value - 1);                                             //递归调用
            }
            [lock unlock];                                                              //解开递归锁，让其他线程可以访问
        };
        
        RecursiveMethod(5);                                                             //首次调用递归的block
    });
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RootVCCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    if (!cell) {
        cell = [[RootVCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
    }
    cell.delegate = self;
    NSLog(@"Row_0 :%@", indexPath);
    @weakify(cell);
    [[cell.rac_prepareForReuseSignal deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(RACUnit *unit) {
        @strongify(cell);
        NSLog(@"unit_1 :%@", unit);
        NSLog(@"cell_2 :%@", cell);
        NSLog(@"indexPath_3 :%@", indexPath);
        NSLog(@"unit :%@", unit);
    }];
    
//    cell.constraint = [self.viewModel.datas objectAtIndex:indexPath.row];
//    
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.viewModel.datas.count > 0) {
        return self.viewModel.datas.count;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"height_4 :%@", indexPath);
    return 44.0f;
//    return [tableView fd_heightForCellWithIdentifier:Identifier cacheByIndexPath:indexPath configuration:^(RootVCCell *cell) {
//        cell.constraint = [self.viewModel.datas objectAtIndex:indexPath.row];
//    }];
}

#pragma mark BaseCellMoveViewStateDelegate

- (void)didCellMoveForGestureStatus:(kCellGestureStatusType)gestrueStatus withObject:(HSYCustomBaseTableViewMoveCell *)cell {
    
    switch (gestrueStatus) {
        case kCellGestureStatusTypeEndOpen: {
            
            self.signCell = cell;
        }
            break;
        
        case kCellGestureStatusTypeShouldOpen: {
         
            if (self.signCell) {
                [self.signCell closeMoveCellWithAnimated:YES];
            }
        }
            break;
            
        case kCellGestureStatusTypeEndClose: {
            
            self.signCell = nil;
        }
            break;
        
        case kCellGestureStatusTypeShouldClose: {
            
        }
            break;
            
        default:
            break;
    }
}

- (void)sendSelectDeleteForCell:(id)cell {
    
    //删除
    if (!cell) {
        return;
    }

    NSIndexPath *indexPath = [self getTableViewIndexPathForCell:(RootVCCell *)cell withTableView:self.tableView];
    if ([self.viewModel deleteDataForIndexPath:indexPath]) {
        [self deleteRowsAtIndexPaths:[NSArray  arrayWithObject:indexPath] withRowDeleteAnimation:UITableViewRowAnimationTop tableView:self.tableView];
    }
}

- (void)sendSelectCancel {
    
    //取消
    if (!self.signCell) {
        return;
    }
    [self.signCell closeMoveCellWithAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
